import React, { PureComponent } from 'react';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select, DatePicker, TreeSelect, message } from 'antd';
import { TradingMarketC, InputC, InputNumberC, SecuritiesCodeC, SelectC, codeType, SecondHeaderC } from '../../../comps';

const { TreeNode } = TreeSelect;
const { Option } = Select;
const FormItem = Form.Item;
import { connect } from 'dva';
import styles from './index.less';

@Form.create()
@connect(({ bondInformationM, globalM }) => ({ bondInformationM, globalM }))
export default class OperateFormC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      issuerList: [], //发行人下拉列表
      tempIssuerList: [], //筛选后的发行人下拉列表
      bondRatingList: [], //债券评级下拉列表
      issuerRatingList: [], //主体评级下拉列表
      unitList: [], // 期限单位下拉列表
      marketData: {}, // 上市转换数据
      BaseInfoData: {}, //转换后的债券基本信息数据
      isserBaseInfoData: {}, // 转换后的发行人基本信息
      marketCodeData: {}, // 正股代码数据
      bondTypeListPBC: [], // 人行债券类型下拉
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    //权限配置
    //获取发行人下拉列表
    this.getIssuerList();
    // 枚举
    const {
      globalM: {
        dataDictionary: { Bond_Type_PBC = [], COMPANY_DICT = [], SMART_BETA_RATING = [], SMART_BETA_CREDITRATING = [] },
      },
    } = this.props;
    this.setState({
      bondRatingList: SMART_BETA_RATING, //债券评级
      issuerRatingList: SMART_BETA_CREDITRATING, //主体评级
      unitList: COMPANY_DICT, //期限单位
      bondTypeListPBC: this.changeTreeData(Bond_Type_PBC), // 人行债券类型下拉
    });
  }

  //获取发行人下拉列表
  getIssuerList = (e) => {
    if (!e) {
      this.props.dispatch({
        type: 'bondInformationM/getIssuerList',
        payload: {},
        callback: (data) => {
          this.setState({
            issuerList: data,
          });
        },
      });
    } else {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        this.props.dispatch({
          type: 'bondInformationM/getIssuerList',
          payload: {
            name: e,
          },
          callback: (data) => {
            if (data) {
              this.setState({
                issuerList: data,
              });
            } else {
              this.setState({
                issuerList: [],
              });
            }
          },
        });
      }, 500);
    }
  };
  // 定金比例校验
  handlePrepaindPropValidator = (rule, val, callback) => {
    if (val > 100) {
      callback('输入值不能大于100！');
    }
    callback();
  };
  // 定金校验
  handlePrepaindAmountValidator = (rule, val, callback) => {
    const {
      form: { getFieldValue },
    } = this.props;
    if (parseFloat(val) > parseFloat(getFieldValue('issueSize'))) {
      callback('输入值不能大于发行总量！');
    }
    callback();
  };
  // 正股代码change事件
  marketChange = (e) => {
    if (e && e !== null) {
      this.setState({
        marketCodeData: e,
      });
      // 债券基本信息
      this.props.dispatch({
        type: 'bondInformationM/queryBondBasicInfoDetail',
        payload: {
          secucode: e.secucode,
        },
        callback: (data) => {
          if (data) {
            this.setState({
              BaseInfoData: data,
            });
          } else {
            this.setState({
              BaseInfoData: {},
            });
          }
        },
      });
      // 发行人基本信息
      this.props.dispatch({
        type: 'bondInformationM/queryBondIssuerInfoDetail',
        payload: {
          bondID: e.secucode,
          exchangeCode: e.exchangeCode,
          tradingCode: e.tradingCode,
        },
        callback: (data) => {
          if (data) {
            this.setState({
              isserBaseInfoData: data,
            });
          } else {
            this.setState({
              isserBaseInfoData: {},
            });
          }
        },
      });
    } else {
      message.warning('请选择正股代码');
    }
  };
  // 债券分类树形
  changeTreeData = (arr) => {
    let tempArr = [];
    arr.forEach((item) => {
      tempArr.push({
        value: item.code,
        title: item.value,
        selectable: !item.children?.length,
        children: this.changeTreeData(item.children || []),
      });
    });
    return tempArr;
  };
  render() {
    const { issuerList, bondTypeListPBC, unitList } = this.state;
    const {
      globalM: {
        dataDictionary: { SUPPLEMENTARY_TOOL_DICT = [] },
      },
    } = this.props;
    const { getFieldDecorator } = this.props.form;
    // 将树形结构的父节点置为 不可选
    const renderTreeNodes = (data) => {
      return data.map((item) => {
        if (item.children && item.children.length !== 0) {
          item.disabled = true;
          return (
            <TreeNode key={item.id} title={item.title} value={item.value} disabled={item.disabled}>
              {renderTreeNodes(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode {...item} key={item.id} title={item.title} value={item.value} />;
      });
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 7, offset: 0 },
        sm: { span: 11, offset: 0 },
        md: { span: 11, offset: 0 },
        lg: { span: 11, offset: 0 },
        xl: { span: 10, offset: 0 },
        xxl: { span: 8, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 15, offset: 0 },
        sm: { span: 11, offset: 0 },
        md: { span: 11, offset: 0 },
        lg: { span: 11, offset: 0 },
        xl: { span: 12, offset: 0 },
        xxl: { span: 14, offset: 0 },
      },
    };
    return (
      <div>
        {this.props.isEdit == '3' ? <SecondHeaderC title={'发行信息'} style={{ marginBottom: '10px' }} /> : null}
        <Form className={styles.bondFormStyle} style={{ marginBottom: '10px' }}>
          {/* ***************************第一行************************************* */}
          <Row>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='债券代码' {...formItemLayout}>
                {getFieldDecorator('tradingCode', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入债券代码' }],
                  getValueFromEvent: (event) => {
                    return event.target.value.replace(/\s+/g, '').replace(/[\W]/g, '');
                  },
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.tradingCode.split(' - ')[0] : undefined,
                })(<Input disabled={this.props.isEdit == '2' || this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='债券名称' {...formItemLayout}>
                {getFieldDecorator('secuabbr', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入债券名称' }],
                  getValueFromEvent: (event) => {
                    return event.target.value.replace(/\s+/g, '');
                  },
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.secuabbr : undefined,
                })(<Input disabled={this.props.isEdit == '2' || this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='债券类型' {...formItemLayout}>
                {getFieldDecorator('secucategoryCodeii', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请选择债券类型' }],
                  initialValue:
                    this.props.isEdit == '2' || this.props.isEdit == '3'
                      ? { value: this.props.editObj.secucategoryCodeii, label: this.props.editObj.secucategoryCodeiiName }
                      : undefined,
                })(
                  <TreeSelect dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} allowClear treeDefaultExpandAll labelInValue treeData={bondTypeListPBC} />,

                  // <Select
                  //     style={{ width: '100%' }}
                  //     allowClear
                  //     labelInValue>
                  //     {bondTypeListPBC.map(item => {
                  //         return <Option value={item.code}>{item.value}</Option>
                  //     })}
                  // </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <TradingMarketC
                form={this.props.form}
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择市场' }]}
                dataIndex={'exchangeCode'}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.exchangeCode : undefined}
                marketType={['jys', 'yhj']}
                formItemLayout={formItemLayout}
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
          </Row>
          {/* ***************************第二行************************************* */}
          <Row>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <InputNumberC
                dataIndex='bondMaturity'
                title={'期限'}
                precision={0}
                min={0}
                splitStyle={true}
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择期限' }]}
                form={this.props.form}
                formItemLayout={formItemLayout}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.bondMaturity : undefined}
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <SelectC
                dataIndex='termUnit'
                form={this.props.form}
                title='期限单位'
                disabled={this.props.isEdit == '3' ? true : false}
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择期限单位' }]}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.termUnit : undefined}
                formItemLayout={formItemLayout}
                dataSource={unitList.map((item) => {
                  return { value: item.code, title: item.value };
                })}
                positionBody={true}
              />
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <InputNumberC
                dataIndex='couponRate'
                title={'利率'}
                unit={'%'}
                min={0}
                precision={2}
                splitStyle={true}
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择利率' }]}
                form={this.props.form}
                formItemLayout={formItemLayout}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? Number((this.props.editObj.couponRate - 0) * 100).toFixed(2) : undefined}
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='发行起始日' {...formItemLayout}>
                {getFieldDecorator('listingStartdate', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入开始时间' }],
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? moment(this.props.editObj.listingStartdate) : moment(),
                })(<DatePicker disabled={this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
          </Row>
          {/* ***************************第三行************************************* */}
          <Row>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='发行截止日' {...formItemLayout}>
                {getFieldDecorator('listingEnddate', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入发行截止日' }],
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? moment(this.props.editObj.listingEnddate) : moment(),
                })(<DatePicker disabled={this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='中签日' {...formItemLayout}>
                {getFieldDecorator('pickingDate', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入中签日' }],
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? moment(this.props.editObj.pickingDate) : moment(),
                })(<DatePicker disabled={this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='缴款日' {...formItemLayout}>
                {getFieldDecorator('fundingDate', {
                  rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入缴款日' }],
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? moment(this.props.editObj.fundingDate) : moment(),
                })(<DatePicker disabled={this.props.isEdit == '3' ? true : false} />)}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <SelectC
                dataIndex='issuer'
                form={this.props.form}
                title='发行人'
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择发行人!' }]}
                multiple={false}
                onSearch={(e) => this.getIssuerList(e)}
                disabled={this.props.isEdit == '3' ? true : false}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.issuerName : undefined}
                formItemLayout={formItemLayout}
                dataSource={issuerList}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                positionBody={true}
              />
            </Col>
          </Row>
          {/* ***************************第四行************************************* */}
          <Row>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='债项评级' {...formItemLayout}>
                {getFieldDecorator('bondRating', {
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.bondRating : undefined,
                })(
                  <Select disabled={this.props.isEdit == '3' ? true : false}>
                    {this.state.bondRatingList &&
                      this.state.bondRatingList.map((item, index) => {
                        return (
                          <Select.Option value={item.value} key={index}>
                            {item.value}
                          </Select.Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <FormItem label='主体评级' {...formItemLayout}>
                {getFieldDecorator('issuerRating', {
                  initialValue: this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.issuerRating : undefined,
                })(
                  <Select disabled={this.props.isEdit == '3' ? true : false}>
                    {this.state.issuerRatingList &&
                      this.state.issuerRatingList.map((item, index) => {
                        return (
                          <Select.Option value={item.value} key={index}>
                            {item.value}
                          </Select.Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <InputNumberC
                dataIndex='issueSize'
                title={'发行总量'}
                unit={'万元'}
                precision={2}
                min={0}
                splitStyle={true}
                rules={[{ required: this.props.isEdit == '3' ? false : true, message: `请输入发行总量` }]}
                form={this.props.form}
                formItemLayout={formItemLayout}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? Number((this.props.editObj.issueSize - 0) / 10000).toFixed(4) : undefined}
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <InputNumberC
                dataIndex='prepaindProp'
                title={'定金比例'}
                unit={'%'}
                precision={2}
                min={0}
                max={100}
                rules={[{ validator: this.handlePrepaindPropValidator }]}
                splitStyle={true}
                onChange={() => {
                  this.props.form.setFieldsValue({
                    prepaindAmount: undefined,
                  });
                }}
                form={this.props.form}
                formItemLayout={formItemLayout}
                initialValue={
                  (this.props.isEdit == '2' || this.props.isEdit == '3') && (this.props.editObj.prepaindProp || this.props.editObj.prepaindProp === 0)
                    ? Number((this.props.editObj.prepaindProp - 0) * 100).toFixed(2)
                    : undefined
                }
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
          </Row>
          <Row>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <InputNumberC
                dataIndex='prepaindAmount'
                title={'定金'}
                unit={'万元'}
                precision={2}
                min={0}
                splitStyle={true}
                onChange={() => {
                  this.props.form.setFieldsValue({
                    prepaindProp: undefined,
                  });
                }}
                rules={[{ validator: this.handlePrepaindAmountValidator }]}
                form={this.props.form}
                formItemLayout={formItemLayout}
                initialValue={
                  (this.props.isEdit == '2' || this.props.isEdit == '3') && (this.props.editObj.prepaindAmount || this.props.editObj.prepaindAmount === 0)
                    ? Number((this.props.editObj.prepaindAmount - 0) / 10000).toFixed(4)
                    : undefined
                }
                disabled={this.props.isEdit == '3' ? true : false}
              />
            </Col>
            <Col span={6} style={{ marginBottom: '10px' }}>
              <SelectC
                dataIndex='supplementaryTool'
                form={this.props.form}
                title='补充工具'
                multiple={false}
                disabled={this.props.isEdit == '3' ? true : false}
                initialValue={this.props.isEdit == '2' || this.props.isEdit == '3' ? this.props.editObj.supplementaryTool : undefined}
                formItemLayout={formItemLayout}
                dataSource={SUPPLEMENTARY_TOOL_DICT.map((item) => {
                  let obj = {
                    title: item.value,
                    value: item.code,
                  };
                  return obj;
                })}
                positionBody={true}
              />
            </Col>
          </Row>
        </Form>
        {this.props.isEdit == '3' ? (
          <>
            <SecondHeaderC title={'上市信息'} style={{ marginBottom: '10px' }} />
            <Row>
              <Col span={6}>
                <SecuritiesCodeC
                  form={this.props.form}
                  dataIndex='marketValue'
                  title='正股代码'
                  codeType={codeType.zq}
                  rules={[{ required: true, message: '请选择正股代码' }]}
                  extraLayout={formItemLayout}
                  onChange={(e) => this.marketChange(e)}
                />
              </Col>
            </Row>
            <Form>
              <Row>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <FormItem label='债券代码' {...formItemLayout}>
                    {getFieldDecorator('tradingCodeMarket', {
                      rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入债券代码' }],
                      getValueFromEvent: (event) => {
                        return event.target.value.replace(/\s+/g, '');
                      },
                      initialValue: this.state.marketCodeData.tradingCode ? this.state.marketCodeData.tradingCode : undefined,
                    })(<Input disabled={true} />)}
                  </FormItem>
                </Col>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <FormItem label='债券名称' {...formItemLayout}>
                    {getFieldDecorator('secuabbrMarket', {
                      rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请输入债券名称' }],
                      getValueFromEvent: (event) => {
                        return event.target.value.replace(/\s+/g, '');
                      },
                      initialValue: this.state.marketCodeData.secuabbr ? this.state.marketCodeData.secuabbr : undefined,
                    })(<Input disabled={true} />)}
                  </FormItem>
                </Col>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <FormItem label='债券类型' {...formItemLayout}>
                    {getFieldDecorator('secucategoryCodeiiMarket', {
                      rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请选择债券类型' }],
                      initialValue: this.state.BaseInfoData.categoryNamei ? this.state.BaseInfoData.categoryNamei : undefined,
                    })(<TreeSelect dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} allowClear treeDefaultExpandAll labelInValue treeData={bondTypeListPBC} />)}
                  </FormItem>
                </Col>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <TradingMarketC
                    form={this.props.form}
                    rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择市场' }]}
                    dataIndex={'exchangeCodeMarket'}
                    initialValue={this.state.marketCodeData.exchangeCode ? this.state.marketCodeData.exchangeCode : undefined}
                    marketType={['jys', 'yhj']}
                    formItemLayout={formItemLayout}
                    disabled={true}
                  />
                </Col>
              </Row>
              <Row>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <FormItem label='发行人' {...formItemLayout}>
                    {getFieldDecorator('issuerMarket', {
                      rules: [{ required: this.props.isEdit == '3' ? false : true, message: '请选择发行人' }],
                      initialValue: this.state.isserBaseInfoData.issuer ? this.state.isserBaseInfoData.issuer : undefined,
                    })(
                      <Select showSearch={true} onSearch={(e) => this.getIssuerList(e)} filterOption={false} disabled={true}>
                        {issuerList.map((item, index) => {
                          return (
                            <Select.Option title={item.value} value={item.title} key={index}>
                              {item.value}
                            </Select.Option>
                          );
                        })}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <InputNumberC
                    dataIndex='couponRateMarket'
                    title={'利率'}
                    unit={'%'}
                    min={0}
                    precision={2}
                    splitStyle={true}
                    rules={[{ required: this.props.isEdit == '3' ? false : true, message: '请选择利率' }]}
                    form={this.props.form}
                    formItemLayout={formItemLayout}
                    initialValue={this.state.BaseInfoData.couponRate ? this.state.BaseInfoData.couponRate : undefined}
                    disabled={true}
                  />
                </Col>
                <Col span={6} style={{ marginBottom: '10px' }}>
                  <InputNumberC
                    dataIndex='issueSizeMarket'
                    title={'发行总量'}
                    unit={'万元'}
                    precision={2}
                    min={0}
                    splitStyle={true}
                    rules={[{ required: this.props.isEdit == '3' ? false : true, message: `请输入发行总量` }]}
                    form={this.props.form}
                    formItemLayout={formItemLayout}
                    initialValue={this.state.BaseInfoData.issueSize ? this.state.BaseInfoData.issueSize : undefined}
                    disabled={true}
                  />
                </Col>
              </Row>
            </Form>
          </>
        ) : null}
      </div>
    );
  }
}
